package org.pan;

import com.google.common.base.Preconditions;
import com.google.common.eventbus.EventBus;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.persist.jpa.JpaPersistModule;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class GuiceFx {

    public static Injector injector;

    public static Parent load(Class<? extends Initializable> controller) {
        log.debug("load parent:{}", controller);
        Preconditions.checkNotNull(injector, "injector 未初始化");
        Controller annotation = controller.getAnnotation(Controller.class);
        if (annotation == null) {
            log.error("未找到@Controller注解");
            throw new RuntimeException();
        }
        try {
            return FXMLLoader.load(controller.getResource(annotation.fxml()), null, null, param -> {
                log.debug("call param:{}", param);
                return injector.getInstance(param);
            });
        } catch (IOException e) {
            log.error("加载fxml异常", e);
            throw new RuntimeException();
        }
    }

    public static void init(Stage primaryStage) {
        log.info("guice init begin");
        injector = Guice.createInjector(binder -> {
            binder.bind(EventBus.class).toInstance(new EventBus("default event bus"));
            binder.bind(Stage.class).toInstance(primaryStage);
        }, new JpaPersistModule("JpaUnit"));
        log.info("guice init success");
    }
}
